# -*- coding: utf-8 -*-
# owner: shenyi
# src/main.py
import uvicorn
from fastapi import FastAPI
from contextlib import asynccontextmanager
from src.core import setup_app, config, logger, register_middlewares
from src.api.health import router as health_router
from src.api.instance import router as instance_router

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动事件
    logger().info("🚀 FastAPI application starting up...")
    # 可在此处初始化数据库连接、缓存等（如果需要）
    yield
    # 关闭事件
    logger().info("🛑 FastAPI application shutting down...")
    # 可在此处关闭连接、清理资源等
    
def create_app() -> FastAPI:
    """创建 FastAPI 应用实例"""
    # 初始化全局配置和日志（必须在 app 创建前调用！）
    setup_app()

    app = FastAPI(
        title="CloudKit API",
        description="Cloud resource management API",
        version="0.1.0",
        debug=config().get("DEBUG", "false").lower() == "true"
    )
    
    # 注册中间件
    register_middlewares(app)

    # 注册路由
    app.include_router(health_router)
    app.include_router(instance_router)

    return app

# 全局 app 实例（供 uvicorn 使用）
app = create_app()

if __name__ == "__main__":
    # 从配置读取 HOST 和 PORT，支持环境变量覆盖
    host = config().get("HOST", "127.0.0.1")
    port = int(config().get("PORT", "8000"))

    logger().info(f"Starting server at http://{host}:{port}")
    uvicorn.run(
        "src.main:app",
        host=host,
        port=port,
        reload=config().get("DEBUG", "false").lower() == "true",  # 开发时自动重载
        log_level="info"
    )